extends Node2D
@onready var server_peer = ENetMultiplayerPeer.new()
@onready var spawn = $MultiplayerSpawner
@onready var _mess = $"../gamemess"
@onready var player_data :Dictionary = {}
@onready var send_id :int


func _ready():
	spawn.spawn_function = Callable(self , "new_spawn_func") #自定义玩家生产方法

func start_game():
	var error = server_peer.create_server(9528,36)
	if error:
		_mess.append_text("[color=red]服务器启动失败：%s[/color]\n" %error)
	else :
		multiplayer.multiplayer_peer = server_peer
		#-----------------------信号连接--------------------------------
		multiplayer.peer_connected.connect(_peer_connected)
		multiplayer.peer_disconnected.connect(_peer_disconnected)
		#----------------------------------------------------------------
		var tim = Time.get_datetime_string_from_system()
		_mess.append_text("[color=green]服务器于系统时间：%s启动[/color]\n" %tim)

func close_game():
	server_peer.close()
	var children = $players.get_children()
	for i in children:
		i.queue_free()
	#--------------------------信号断开------------------------------
	multiplayer.peer_connected.disconnect(_peer_connected)
	multiplayer.peer_disconnected.disconnect(_peer_disconnected)
	#----------------------------------------------------------------
	var tim = Time.get_datetime_string_from_system()
	_mess.append_text("[color=black]服务器于系统时间：%s停止[/color]\n" %tim)


func _peer_connected(id): #玩家进入时，信号自动调用，参数为加入游戏的客户端ID
	_mess.append_text("客户端进入，ID为： " + str(id) + "\n")


func  _peer_disconnected(id): #玩家退出时，信号自动调用，参数为退出游戏的客户端ID
	_mess.append_text("客户端退出 ，ID为： " + str(id) + "\n")
	$players.get_node(str(id)).queue_free()  #删除退出的客户端	

func new_spawn_func(data:Variant):
	if data.is_empty():
		return
	else :
		var p = load("res://players.tscn").instantiate()
		var k = data[0]
		p.name = str(send_id)
		return p
		

@rpc("any_peer","call_local")
func spawn_p(data :Array):
	send_id = multiplayer.get_remote_sender_id()
	var online_player = player_data.find_key(data) #查找是不是已经登录的玩家
	
	if online_player != null:   
		spawn.spawn(data)
		server_peer.disconnect_peer(online_player) #提出重复登录玩家
		player_data.erase(online_player)
	else :
		spawn.spawn(data)
	player_data[send_id] = data
	print(player_data)

@rpc("any_peer","call_local")
func _animation():
	pass
